package com.huluobo.a2307monthdemo2.video

import android.content.Intent
import android.util.Log
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.Animation.AnimationListener
import android.view.animation.AnimationUtils
import android.view.animation.BounceInterpolator
import android.widget.EditText
import androidx.core.content.ContentProviderCompat.requireContext
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.OnScrollListener
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2307monthdemo2.R
import com.huluobo.a2307monthdemo2.adapter.CommentAdapter
import com.huluobo.a2307monthdemo2.adapter.MultiVideoAdapter
import com.huluobo.a2307monthdemo2.adapter.VideoAdapter
import com.huluobo.a2307monthdemo2.databinding.FragmentVideoBinding
import com.huluobo.a2307monthdemo2.live.LiveActivity
import com.huluobo.a2307monthdemo2.login.LoginActivity
import com.huluobo.lib_base.bean.VideoBean
import com.huluobo.lib_base.mvvm.BaseFragment
import com.huluobo.lib_base.mvvm.MessageEvent
import com.huluobo.lib_base.net.Const
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer
import com.umeng.socialize.ShareAction
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import org.greenrobot.eventbus.EventBus

class VideoFragment : BaseFragment<FragmentVideoBinding, VideoViewModel>() {
    private lateinit var videoAdapter: MultiVideoAdapter

    private var currentPosition = 0
    private lateinit var player: StandardGSYVideoPlayer

    private lateinit var commentAdapter: CommentAdapter
    override fun initData() {
        vm.getVideos(2, 20)
        vm.getVideosSuccess.observe(this) {
            videoAdapter.data.clear()
            videoAdapter.data.addAll(it)
            videoAdapter.notifyDataSetChanged()
        }

        vm.likeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            videoAdapter.data[currentPosition].dianzan = 1
            videoAdapter.notifyItemChanged(currentPosition)
        }

        vm.unLikeVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
            videoAdapter.data[currentPosition].dianzan = 0
            videoAdapter.notifyItemChanged(currentPosition)
        }

        vm.followAuthSuccess.observe(this) {
            ToastUtils.showLong(it)
            videoAdapter.data[currentPosition].guanzhu = 1
            videoAdapter.notifyItemChanged(currentPosition)
        }

        vm.getCommentSuccess.observe(this) {
            commentAdapter.data.clear()
            commentAdapter.data.addAll(it.sortedByDescending { it.createtime })
            commentAdapter.notifyDataSetChanged()
        }

        vm.sendCommentSuccess.observe(this) {
            commentAdapter.data.addAll(0, it)
            commentAdapter.notifyDataSetChanged()
            val editText = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
            editText.text.clear()
        }

        vm.collectVideoSuccess.observe(this) {
            ToastUtils.showLong(it)
        }
    }

    override fun initView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        binding.videoRv.layoutManager = linearLayoutManager
        videoAdapter = MultiVideoAdapter()
        binding.videoRv.adapter = videoAdapter

        val pagerSnapHelper = PagerSnapHelper()
        pagerSnapHelper.attachToRecyclerView(binding.videoRv)

        binding.videoRv.addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                currentPosition = linearLayoutManager.findFirstVisibleItemPosition()
                player =
                    videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_player) as StandardGSYVideoPlayer
//                player.startPlayLogic()
            }
        })

        videoAdapter.addChildClickViewIds(
            R.id.item_videos_like_iv,
            R.id.item_videos_add_iv,
            R.id.item_videos_comment_iv,
            R.id.item_videos_close_iv,
            R.id.item_videos_comment_send_iv,
            R.id.item_videos_collect_iv,
            R.id.item_videos_share_iv,
            R.id.item_videos_live_cl,
            R.id.item_videos_full_cl
        )
        videoAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (SPUtils.getInstance().getString(Const.PARAM_TOKEN).isNullOrEmpty()) {
                startAct(LoginActivity::class.java)
            } else {
                val videoBean = videoAdapter.data[position]
                when (view.id) {
                    R.id.item_videos_like_iv -> likeVideo(videoBean)
                    R.id.item_videos_add_iv -> followAuth(videoBean)
                    R.id.item_videos_comment_iv -> openComment(videoBean)
                    R.id.item_videos_close_iv -> closeComment()
                    R.id.item_videos_comment_send_iv -> sendComment(videoBean)
                    R.id.item_videos_collect_iv -> collectVideo(videoBean)
                    R.id.item_videos_share_iv -> shareVideo(videoBean)
                    R.id.item_videos_live_cl -> toLive(videoBean)
                    R.id.item_videos_full_cl -> fullScreen()
                }
            }
        }
    }

    private fun fullScreen() {
        player.isRotateViewAuto = true
        player.startWindowFullscreen(requireContext(), false, false)
    }

    private fun toLive(videoBean: VideoBean) {
        val intent = Intent(requireContext(), LiveActivity::class.java)
        intent.putExtra(Const.KEY_VIDEO_BEAN, videoBean)
        startActivity(intent)
    }

    private fun shareVideo(videoBean: VideoBean) {
        val umImage = UMImage(requireContext(), videoBean.videomainimg)
        umImage.compressStyle = UMImage.CompressStyle.SCALE

        val umWeb = UMWeb(videoBean.videopath)
        umWeb.title = videoBean.authname
        umWeb.setThumb(umImage)
        umWeb.description = videoBean.caption

        ShareAction(requireActivity())
            .withMedia(umWeb)
            .open()
    }

    private fun collectVideo(videoBean: VideoBean) {
        vm.collectVideo(videoBean)
    }

    private fun sendComment(videoBean: VideoBean) {
        val editText = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_et) as EditText
        val msg = editText.text.toString().trim()
        if (msg.isNotEmpty()) {
            val map = mapOf(
                Const.PARAM_VIDEO_ID to videoBean.id,
                Const.PARAM_MSG to msg
            )
            vm.sendComment(map)
        }
    }

    private fun closeComment() {
        val commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        if (commentLayout != null) {
            val animOut = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_out)
            animOut.duration = 500
            animOut.interpolator = AccelerateInterpolator()
            animOut.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    commentLayout.visibility = View.GONE
                    binding.videoRv.setInterceptor(true)
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animOut)
        }
    }

    private fun openComment(videoBean: VideoBean) {
        binding.videoRv.setInterceptor(false)
        val commentLayout = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_ll)
        if (commentLayout != null) {
            commentLayout.visibility = View.VISIBLE
            val commentRv = videoAdapter.getViewByPosition(currentPosition, R.id.item_videos_comment_rv) as RecyclerView
            commentRv.layoutManager = LinearLayoutManager(requireContext())
            commentAdapter = CommentAdapter(vm, this, videoBean.id)
            commentRv.adapter = commentAdapter

            val animIn = AnimationUtils.loadAnimation(requireContext(), R.anim.anim_in)
            animIn.duration = 500
            animIn.interpolator = BounceInterpolator()
            animIn.setAnimationListener(object : AnimationListener {
                override fun onAnimationStart(animation: Animation?) {
                    vm.getComment(videoBean.id)
                }

                override fun onAnimationEnd(animation: Animation?) {
                }

                override fun onAnimationRepeat(animation: Animation?) {
                }
            })
            commentLayout.startAnimation(animIn)
        }
    }

    private fun followAuth(videoBean: VideoBean) {
        val map = mapOf(
            Const.PARAM_AUTHNAME to videoBean.authname
        )
        vm.followAuth(map)
    }

    private fun likeVideo(videoBean: VideoBean) {
        if (videoBean.dianzan == 0) {
            vm.likeVideo(videoBean.id)
        } else {
            vm.unLikeVideo(videoBean.id)
        }
    }

    override fun onEvent(messageEvent: MessageEvent) {
        super.onEvent(messageEvent)
        if (messageEvent.message == "1") {
            videoAdapter.data[currentPosition].guanzhu = 1
        } else {
            videoAdapter.data[currentPosition].guanzhu = 0
        }
    }
}